//////////////////////////////////////////////////////////////////////////
#include <FileSystem/FileSystem.hpp>
#include <FileSystem/SfmlStream.hpp>
#include <physfs.h>


using namespace FileSystem;


SfmlStream::SfmlStream()
:	mHandle( nullptr )
{
}


SfmlStream::~SfmlStream()
{
	if( mHandle )
		PHYSFS_close( (PHYSFS_File*)mHandle );
}


SfmlStream* SfmlStream::Open( const std::string& file )
{
	PHYSFS_File*	pfile	=	PHYSFS_openRead( file.c_str() );
	if( pfile!=nullptr )
	{
		SfmlStream*	result	=	new SfmlStream();
		if( result!=nullptr )
		{
			result->mHandle	=	pfile;
			return result;
		}
		PHYSFS_close( pfile );
	}
	return nullptr;
}


SfmlStream* SfmlStream::Write( const std::string& file )
{
	PHYSFS_File*	pfile	=	PHYSFS_openWrite( file.c_str() );
	if( pfile!=nullptr )
	{
		SfmlStream*	result	=	new SfmlStream();
		if( result!=nullptr )
		{
			result->mHandle	=	pfile;
			return result;
		}
		PHYSFS_close( pfile );
	}
	return nullptr;
}


sf::Int64 SfmlStream::read( void* data, sf::Int64 size )
{
	return PHYSFS_read( (PHYSFS_File*)mHandle, data, 1, PHYSFS_uint32( size ) );
}


sf::Int64 SfmlStream::seek( sf::Int64 position )
{
	return PHYSFS_seek( (PHYSFS_File*)mHandle, position );
}


sf::Int64 SfmlStream::tell()
{
	return PHYSFS_tell( (PHYSFS_File*)mHandle );
}


sf::Int64 SfmlStream::getSize()
{
	return PHYSFS_fileLength( (PHYSFS_File*)mHandle );
}
